package com.crm.base.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.base.domain.AjaxResult;
import com.crm.base.domain.LoginUser;
import com.crm.base.domain.Menu;
import com.crm.base.domain.User;
import com.crm.base.utils.JWTUtils;
import com.crm.base.mapper.MenuMapper;
import com.crm.base.mapper.UserMapper;
import com.crm.base.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-07-12
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {



    private AuthenticationManager manager;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public AjaxResult login(User user) {
        UsernamePasswordAuthenticationToken u = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = manager.authenticate(u);
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        loginUser.getUser().setPassword("");

        //登陆成功
        List<String> all = userMapper.findAllByPermissions(user);

        loginUser.getUser().setPermissions(all);

        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", loginUser.getUser().getUid());
        map.put("permissions", loginUser.getUser().getPermissions());


        //jwt  生成
        String data = JWTUtils.create(map);


//        String token = UUID.randomUUID().toString().replaceAll("-", "");

//        redisTemplate.opsForValue().set("user:info:" + token, loginUser.getUser());

        return AjaxResult.me().setData(data);
    }


    public AjaxResult findMenuList(Long uid) {

        HashMap<String, Object> map = new HashMap<>();
        List<Menu> menus = menuMapper.findMenus(uid);
        // 处理菜单
        List<Menu> menu = buildMenu(menus);
        map.put("menuList", menu);
        return AjaxResult.me(map);


    }

    private List<Menu> buildMenu(List<Menu> menus) {

        Map<Long, Menu> map = new HashMap<>();
        // 第一步：将所有菜单项放入Map中
        menus.forEach(m -> map.put(m.getMid(), m));

        // 第二步：寻找儿子，并回到他爸爸家里
        menus.forEach(m -> {
            if (map.containsKey(m.getParent())) {
                Menu parent = map.get(m.getParent());
                parent.addChild(m);
            }
        });

        // 第三步：从Map中提取顶级菜单项
        return map.values().stream().filter(m -> {
            return Objects.isNull(m.getParent());
        }).collect(Collectors.toList());
    }
}
